package com.satan.fmmall.utils;

import com.satan.fmmall.vo.ResCode;
import com.satan.fmmall.vo.ResultVo;
import io.jsonwebtoken.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName JwtUitls
 * @Description TODO
 * @date 2022/4/2 13:17
 * @Version 1.0
 */

public class JwtUitls {
    //设置签名密钥
    private static final String tokenSignKey = "satan@1996";

    //根据用户id创建token
    public static String createToken(Integer userId) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);
        JwtBuilder jwtBuilder = Jwts.builder()
                .setId(userId.toString())//设置用户id为token id
                .setClaims(claims)//claims中可以存放用户的角色权限信息
                .setExpiration(new Date(System.currentTimeMillis() +  24 * 60 *60 *1000)) //设置过期时间
                .setIssuedAt(new Date())//设置token生成的时间
                .signWith(SignatureAlgorithm.HS256, tokenSignKey);//设置加密方式和加密密码
        String token = jwtBuilder.compact();
        return token;
    }

    public static ResultVo checkToken(String token) {
        try {
            //验证token
            JwtParser parser = Jwts.parser();
            parser.setSigningKey(tokenSignKey);
            Jwt parse = parser.parse(token);
            return ResultVo.success(null);
        }catch (ExpiredJwtException e){
            return ResultVo.fail(ResCode.LOGIN_TIME_OUT);
        }catch (UnsupportedJwtException e){
            return ResultVo.fail(ResCode.TOKEN_ERROR);
        }catch (Exception e){
            return ResultVo.fail(ResCode.LOGIN_TRY_AGAIN);
        }

    }
    public static Integer getUserId(String token){
        if("".equals(token)||token==null) return null;
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        Integer userId = (Integer)claims.get("userId");
        return userId;
    }
    public static void main(String[] args) {
        String token = JwtUitls.createToken(1);
        System.out.println("token = " + token);
        ResultVo resultVo = JwtUitls.checkToken("eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NDg4ODA4MzMsInVzZXJJZCI6MSwiaWF0IjoxNjQ4ODgwODMwfQ.7Zk2Tq00L8QR6Sq8yH8qv2tRlGKYb3QYi9kcwmfwJnc");
        System.out.println(resultVo);
    }

}
